package learnjava.basic.other;

import java.lang.annotation.*;
import java.lang.reflect.Field;

//练习反射操作注解

public class TestReflectAnno {

    public static void main(String[] args) throws Exception {
        Class aClass = Class.forName("learnjava.basic.other.Student");

        //通过反射获取所有注解
        Annotation[] annotations = aClass.getAnnotations();
        for (Annotation a: annotations) {
            System.out.println(a);
        }
        //获得类的注解
        TableKuang tableKuang = (TableKuang) aClass.getAnnotation(TableKuang.class);
        System.out.println(tableKuang.value());
        //获得成员变量的注解
        Field f = aClass.getDeclaredField("name");
        FieldKuang annos = f.getAnnotation(FieldKuang.class);
        System.out.println(annos.columnName());
        System.out.println(annos.type());
        System.out.println(annos.length());
    }
}


@TableKuang("db_student")
class Student{
    @FieldKuang(columnName = "db_id",type = "int", length = 10)
    private int id;
    @FieldKuang(columnName = "db_age",type = "int", length = 10)
    private int age;
    @FieldKuang(columnName = "db_name",type = "varchar", length = 3)
    private String name;

    public Student(int id, int age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableKuang{
    String value();
}

//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldKuang{
    String columnName();
    String type();
    int length();
}
